package com.oc.mba.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import com.oc.mba.entity.OcDevices;
import com.oc.mba.service.DeviceService;
import com.oc.mba.util.CommConsts;
import com.oc.mba.util.CommLog;
import com.oc.mba.util.JsonUtil;
import com.oc.mba.util.MD5;
import com.oc.mba.util.OcConfig;
import com.oc.mba.util.ResultCode;
import com.oc.mba.util.SpringUtil;

/**
 * 分发控制
 * @author unidw
 *
 */
public class DispatcherController extends BaseController {
	private static final CommLog logger = new CommLog(DispatcherController.class);

	/**
	 * 分发逻辑
	 * @param request 请求
	 * @param response 响应
	 * @throws Exception 异常
	 */
	public void dispatch(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		logger.info("dispatch");
		
		// 校验是否包含req参数
		String req = request.getParameter(CommConsts.REQ_FLAG);
		req = req.trim();
		if (req == null || req.equals("")) {
			logger.error("request params is empty.");
			resultJson(response, genError(ResultCode.EMPTY_REQ));
			return;
		}
		
		// 非JSON格式
		if (!JsonUtil.mayBeJSON(req)) {
			resultJson(response, genError(ResultCode.INVALID_REQ_TYPE));
			return;
		}
		
		JSONObject reqJSON = JsonUtil.jsonSTO(req);
		
		if (!isValidReq(reqJSON)) {
			// 返回异常
			logger.error("invalid request params. req=" + req);
			resultJson(response, genError(ResultCode.INVALID_REQ));
			return;
		}
		
		WrappedReq wReq = new WrappedReq();
		wReq.setSignID(reqJSON.getString(CommConsts.SIGNID_FLAG));
		wReq.setContent(reqJSON);
		logger.info("Req=" + wReq);
		// 注册接口不需要解密
		if (wReq.getSignID().equals("100")) {
			resultJson(response, doDispatch(wReq, request, response));
			return;
		}
		// 解密
		else {
			// 不包含deviceID
			if (!wReq.getContent().containsKey(CommConsts.DEVICE_ID)) {
				logger.error("Req params did't contain deviceID. req=" + wReq);
				resultJson(response, genError(ResultCode.INVALID_REQ));
				return;
			}
			// 不包含安全认证KEY
			else if (!wReq.getContent().containsKey(CommConsts.SECURE_KEY)) {
				logger.error("Req params did't contain secure key. req=" + wReq);
				resultJson(response, genError(ResultCode.INVALID_REQ));
				return;
			}
			else {
				// 设备ID
				Integer deviceID = wReq.getContent().getInt(CommConsts.DEVICE_ID);
				// 安全认证KEY
				String secureKey = wReq.getContent().getString(CommConsts.SECURE_KEY);
				// 安全认证KEY为空
				if (secureKey== null || secureKey.equals("")) {
					logger.error("Empty secure key. req=" + wReq);
					resultJson(response, genError(ResultCode.INVALID_REQ));
					return;
				}
				DeviceService deviceService = (DeviceService) SpringUtil.getBean("deviceServiceImpl");
				OcDevices device = deviceService.findById(deviceID);
				// 设备不存在
				if (device==null) {
					logger.error("Device not exist. req=" + wReq);
					resultJson(response, genError(ResultCode.INVALID_REQ));
					return;
				}
				// 六位随机数
				String randomStr = secureKey.substring(0, 6);
				String androidID = device.getAid();
				String tmpSecure = randomStr + MD5.encryptHex(randomStr + androidID);
				if (!tmpSecure.equals(secureKey)) {
					logger.error("Invalid Secure Key. Req=" + wReq);
					resultJson(response, genError(ResultCode.INVALID_REQ));
					return;
				}
			}
		}
		// TODO 验证Cookies
		// 返回操作结果
		resultJson(response, doDispatch(wReq, request, response));
	}

	private String doDispatch(WrappedReq wReq, HttpServletRequest request, HttpServletResponse response){
		
		try {
			IController controller = (IController) SpringUtil.getBean(getControllerName(wReq.getSignID()));
			return controller.progress(wReq, request, response);
		} catch (Exception e) {
			e.printStackTrace();
			return genError(ResultCode.INVALID_REQ);
		}
		
	}

	private String getControllerName(String signID) throws Exception {
		String controllerName = OcConfig.getControllerName(signID);
		if (controllerName != null) {
			return controllerName;
		}
		throw new Exception();
	}
	
	public static void main(String[] args) {
		String key = "84b9925d7860f49b3189b5d01624662fa4b449";
		String androidID = "4df20f0e51be28a8";
		String randomStr = key.substring(0, 6);
		String tmpSecure = MD5.encryptHex(randomStr + androidID);
		// 六位随机数
		System.out.println(randomStr);
		System.out.println(tmpSecure);
	}

}
